package com.water_work_form.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.water_work_form.entity.BasicRestriction;
import com.water_work_form.entity.RecordCapacityAnalysis;
import com.water_work_form.entity.dto.CapacityAnalysisDTO;
import com.water_work_form.mapper.*;
import com.water_work_form.mapper.dto.CapacityAnalysisMapper;
import com.water_work_form.service.RecordCapacityAnalysisService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 记录——容量分析（总硬度、总碱度、氯化物、高猛酸盐指数）原始记录 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordCapacityAnalysisServiceImpl extends ServiceImpl<RecordCapacityAnalysisMapper, RecordCapacityAnalysis> implements RecordCapacityAnalysisService {

    @Autowired
    RecordCapacityAnalysisMapper recordCapacityAnalysisMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Autowired
    BasicDeviceMapper basicDeviceMapper;

    @Autowired
    BasicRestrictionMapper basicRestrictionMapper;

    @Autowired
    BasicPhMapper basicPhMapper;

    @Autowired
    BasicFormulaMapper basicFormulaMapper;

    @Autowired
    BasicVolumeMapper basicVolumeMapper;

    @Autowired
    BasicCurveMapper basicCurveMapper;

    @Autowired
    BasicDrugMapper basicDrugMapper;

    @Autowired
    CapacityAnalysisMapper capacityAnalysisMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;

    /**
     * 容量分析（总硬度、总碱度、氯化物、高猛酸盐指数）原始记录 项目查询
     * @param checkStartDate 检测日期（check_date）范围查询开始日期 若非空查询check_date大于checkStartDate数据
     * @param checkEndDate 检测日期（check_date）范围查询结束日期  若非空查询check_date小于checkEndDate数据
     * @param checkSite 检测地点（check_site） 若非空进行模糊查询
     * @param status 状态（status） 若非空进行匹配查询
     * @param current 分页 当前页
     * @param size 分页 每页数据量
     * @return 返回相应数据 按照状态（status）、领样日期（receive_date）、检测日期（check_date）的顺序进行升序排序
     */
    @Override
    public IPage<RecordCapacityAnalysis> selectRecordCapacityAnalysis(String checkStartDate, String checkEndDate, String checkSite, String status, Integer current, Integer size){
        QueryWrapper<RecordCapacityAnalysis> queryWrapper = new QueryWrapper<>();
        if(!checkStartDate.isEmpty() && !checkEndDate.isEmpty()){
            queryWrapper.ge("check_date", checkStartDate).le("check_date", checkEndDate);
        }
        if(!checkSite.isEmpty()){
            queryWrapper.like("check_site", checkSite);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByAsc("status", "receive_date", "check_date");
        IPage<RecordCapacityAnalysis> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 容量分析（总硬度、总碱度、氯化物、高猛酸盐指数）原始记录 基础表数据查询
     * @param formName form表name
     * @param type device表type
     * @param name1 formula表name，drug表name，ph表name，restriction表name
     * @param name2 formula表name，drug表name，ph表name，restriction表name
     * @param name3 formula表name，drug表name，ph表name，restriction表name
     * @param name4 formula表name，drug表name，ph表name，restriction表name
     * @param volume1 volume表name
     * @param volume2 volume表name
     * @param volume3 volume表name
     * @param volume4 volume表name
     * @return 返回相应数据 唯一查询项键名为表名，非唯一项键名数字编号与查询项一致
     */
    @Override
    public Map<String,Object> selectBasicCapacityAnalysis(String formName, String type, String name1, String name2, String name3, String name4, String volume1, String volume2,
                                                          String volume3, String volume4) {
        Map<String,Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(formName));
        map.put("device", basicDeviceMapper.listByName(type));
//        QueryWrapper<BasicRestriction> queryWrapper = new QueryWrapper<>();
//        map.put("restriction", basicRestrictionMapper.selectList(queryWrapper.eq("name", name1)));
        QueryWrapper<CapacityAnalysisDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.name", name1).or().eq("a.name", name2).or().eq("a.name", name3).or().eq("a.name", name4).orderByAsc("c.num")
                .select("a.name", "a.standard_basis", "a.analysis_method", "b.name", "b.concentration", "b.standard_date", "c.formula_content");
        List<CapacityAnalysisDTO> capacityAnalysisDTOS = capacityAnalysisMapper.selectList(queryWrapper);
        Map<String, Object> restriction = new HashMap<>();
        Map<String, Object> ph = new HashMap<>();
        Map<String, Object> formula = new HashMap<>();
        for (CapacityAnalysisDTO capacityAnalysisDTO : capacityAnalysisDTOS) {
            Map<String, String> map1 = new HashMap<>();
            map1.put("name", capacityAnalysisDTO.getName());
            map1.put("standardBasis", capacityAnalysisDTO.getStandardBasis());
            map1.put("analysisMethod", capacityAnalysisDTO.getAnalysisMethod();
        }
        map.put("restriction1", basicRestrictionMapper.getOneByName(name1));
        map.put("restriction2", basicRestrictionMapper.getOneByName(name2));
        map.put("restriction3", basicRestrictionMapper.getOneByName(name3));
        map.put("restriction4", basicRestrictionMapper.getOneByName(name4));
        map.put("ph1", basicPhMapper.getOneByName(name1));
        map.put("ph2", basicPhMapper.getOneByName(name2));
        map.put("ph3", basicPhMapper.getOneByName(name3));
        map.put("ph4", basicPhMapper.getOneByName(name4));
        map.put("formula1", basicFormulaMapper.getOneByName(name1));
        map.put("formula2", basicFormulaMapper.getOneByName(name2));
        map.put("formula3", basicFormulaMapper.getOneByName(name3));
        map.put("formula4", basicFormulaMapper.getOneByName(name4));

        map.put("drug1", basicDrugMapper.listByName(name1));
        map.put("drug2", basicDrugMapper.listByName(name2));
        map.put("drug3", basicDrugMapper.listByName(name3));
        map.put("drug4", basicDrugMapper.listByName(name4));
        map.put("volume1", basicVolumeMapper.getOneByName(volume1));
        map.put("volume2", basicVolumeMapper.getOneByName(volume2));
        map.put("volume3", basicVolumeMapper.getOneByName(volume3));
        map.put("volume4", basicVolumeMapper.getOneByName(volume4));
        return map;
    }

    /**
     * 记录——容量分析（总硬度、总碱度、氯化物、高猛酸盐指数）原始记录 数据表导出
     * @param recordCapacityAnalysis 需要导出的数据表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordCapacityAnalysis(RecordCapacityAnalysis recordCapacityAnalysis) throws IOException {

        Map<String, Object> data = new HashMap<String, Object>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        JSONObject permanganate =  JSON.parseObject(recordCapacityAnalysis.getPermanganate());
        JSONObject hardness =  JSON.parseObject(recordCapacityAnalysis.getHardness());
        JSONObject chloride =  JSON.parseObject(recordCapacityAnalysis.getChloride());
        JSONObject alkalinity =  JSON.parseObject(recordCapacityAnalysis.getAlkalinity());

        data.put("receiveDate", dateFormat.format(recordCapacityAnalysis.getReceiveDate()));
        data.put("checkDate", dateFormat.format(recordCapacityAnalysis.getCheckDate()));
        data.put("permanganate", permanganate);
        data.put("hardness", hardness);
        data.put("chloride", chloride);
        data.put("alkalinity", alkalinity);
        data.put("list", recordCapacityAnalysis);

        //渲染文件
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordCapacityAnalysis.docx");
        compile.render(data);
        //输出为文件，指定输出文件名
        compile.writeToFile(destFilePath + recordCapacityAnalysis.getId() + "out_recordCapacityAnalysis.docx");
        compile.close();
    }


}
